package com.thekernel.youdaoyun.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {

    /**
     * 获取 IP 地址
     * 使用 Nginx 等反向代理软件, 则不能通过 request.getRemoteAddr() 获取 IP 地址
     * 如果使用多级反向代理的话, X-Forwarded-For 的值并不止一个, 而是一串 IP 地址, X-Forwarded-For 中第一个非 unknown 的有效 IP 字符串, 则为真实 IP 地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
